
$(document).ready(function(){
	layui.use([ 'layer', 'form', 'element', 'table', 'laydate' ],function() {
		var layer = layui.layer, form = layui.form, element = layui.element, table = layui.table, laydate = layui.laydate;
		createCooperative();
			
	})
	
});
var loading;
// 合作伙伴数据接口
function createCooperative(data,isPage){
	loading = layer.load(2, {time: 0}); 
	var cooperativeJson = data || {};
	cooperativeJson.pageSize=$(".tablePageSize").eq(0).val();
	cooperativeJson.pageNo=isPage?isPage:$(".gotoPageNo").eq(0).val();
	postJsonWithConsoleHeaderToken(api_config.list_Portal_Cooperative, cooperativeJson, function(jsonData){ 
	    if(jsonData.resultCode==200){ 
	    	layer.close(loading);
	    	console.log(jsonData.list);
  			cooperativeList(jsonData);
	    }else{
	        // alert("您已经久未操作,请重新登录!",gotoLogin());
	    }
	});
}

// 创建合作伙伴数据
function cooperativeList(jsonData){
	var cooperativeJson = jsonData.list;
	var array = []
    for(var i = 0; i < cooperativeJson.length; i++){
    	var releaseTime = formatDateToStrWithoutSecend(cooperativeJson[i].releaseTime)
    	array[i]={
    		"a1":"<img src="+system_config.public_file_host_url+cooperativeJson[i].logoUrl+" width=46 height=30 >"
			,"a2":cooperativeJson[i].cooperativeName
			,"a3":cooperativeJson[i].cooperativeUrl
			,"a4":cooperativeJson[i].sort
			,"a5":releaseTime
			,"a6":"<a class='layui-btn layui-btn-decoration layui-btn-xs bluesize layui-hide' function-id='0604000002' detailid="+cooperativeJson[i].id+">详情</a>"+
				  "<a class='layui-btn layui-btn-decoration layui-btn-xs bluesize layui-hide' function-id='0604000003' editid="+cooperativeJson[i].id+">修改</a>"+
				  "<a class='layui-btn layui-btn-decoration layui-btn-xs bluesize layui-hide' function-id='0604000004' delid="+cooperativeJson[i].id+">删除</a>"
    	}
    }
    layui.use(['layer', 'form', 'element','table','laydate'], function(){
	  	var layer = layui.layer
	     	,form = layui.form
	      	,element = layui.element
	      	,table = layui.table
	      	,laydate = layui.laydate;
	    laydate.render({
	        elem: '#test1' //指定元素
	  	});

		//展示已知数据
		table.render({
		    elem: '#SAtable'
		    ,cols: [[ //标题栏
				{field:'a1', title:'Logo'}
		        ,{field:'a2',  title:'名称'}
		        ,{field:'a3',  title:'链接地址'}
		        ,{field:'a4',  title:'排序编号'}
		        ,{field:'a5',  title:'发布时间'}
		        ,{field:'a6',  title:'操作'}
		    ]]
		    ,data: array
		    ,size:'lg'
		    ,even:true
		    ,cellMinWidth:200
		    ,limit: $(".tablePageSize").eq(0).val()
		    ,skin:"line"
		    ,align:"center"
		    ,page: false //是否显示分页
		});
		renderPageToolBar(jsonData, "pagination", "createCooperative()");
		dataReadyCheckPermission();

		// 查看数据
		for (var i = 0; i < cooperativeJson.length; i++) {
			(function(i){
				$('a[detailid]').eq(i).click(function(){
					createPopup("合作伙伴详情")
					var detailid = $(this).attr('detailid');
					var getData = {};
					getData.id = detailid;
					showCooperative(getData);
					$("#imgSubmitBtn").hide();
					$("#cooperativeForm").find("input").attr("disabled", true);
					$("#bizNewsSubmitBtn").hide();
				})
			})(i)
		}

		// 修改数据
		for (var i = 0; i < cooperativeJson.length; i++) {
			(function(i){
				$('a[editid]').eq(i).click(function(){
					createPopup("修改合作伙伴")
					var editid = $(this).attr('editid');
					var getData = {};
					getData.id = editid;
					showCooperative(getData);
					$("#bizNewsSubmitBtn").attr("operateState", "edit");
					$("#bizNewsSubmitBtn").attr("editid", editid);
				})
			})(i)
		}

		// 删除数据
  		for (var i = 0; i < cooperativeJson.length; i++) {
			(function(i){
				$('a[delid]').eq(i).click(function(){
					promptBox();
					var delid = $(this).attr("delid")
					$("#confirmBtn").attr("delid", delid);
				})
			})(i)
		}
	})
}

// 添加数据
$('#addDataBtn').click(function(){
	createPopup("添加合作伙伴")
})

// 确认删除按钮
function promptBox(){
	var popup = '<div class="layui-row">'+
                    '<div class="layui-col-md12 layui-hint">'+
                    	'<p>您真的确定要删除吗？请确定！</p>'+
                    '</div>'+
                    '<div class="layui-col-md12 layui-hint-btn">'+
                        '<button type="button" class="layui-btn confirm" id="confirmBtn">确认</button>'+
                        '<button type="button" class="layui-btn cancel" id="cancelBtn">取消</button>'+
                    '</div>'+
                '</div>';
	var hint = layer.open({
		type: 1,
		area: ['360px','160px'],
		title: "提示信息", 
		resize: false,
		content : popup,
		success: function(layero, index){
		},
		cancel: function(index, layero){ 
		}    
	});

	// 关闭弹出层
	$("#cancelBtn").click(function(){
		layer.close(hint); 
	})

	//  确认删除
	$("#confirmBtn").click(function(){
		var delData = {};
		delData.id = $(this).attr('delid');
		postJsonWithConsoleHeaderToken(api_config.delete_Portal_Cooperative, delData, function(jsonData){ 
		    if(jsonData.resultCode==200){
		        createCooperative();
		         layer.close(hint); 
		         laeyer.msg('删除成功');
		    }else{
		    	layer.msg(jsonData.resultMessage);
		        // alert("您已经久未操作,请重新登录!",gotoLogin());
		    }
		});
	})
}

// 显示数据
function showCooperative(data){
	postJsonWithConsoleHeaderToken(api_config.get_Portal_Cooperative, data, function(jsonData){ 
	    if(jsonData.resultCode==200){
	        console.log(jsonData)
	        $("#cooperativeName").val(jsonData.cooperativeName)
			$("#cooperativeUrl").val(jsonData.cooperativeUrl)
			$("#sort").val(jsonData.sort)
			var logoUrl = system_config.public_file_host_url+jsonData.logoUrl;
			$("#picUrl").attr("src", logoUrl);
			$("#logoUrl").val(jsonData.logoUrl)
	    }else{
	        // alert("您已经久未操作,请重新登录!",gotoLogin());
	    }
	});
}

// 弹出层
function createPopup(headTitle){
    var popupContent = '<form class="layui-form" id="cooperativeForm">'+
                            '<div class="layui-form-item layui-input-container taxIdentificationNumber-container">'+
                                '<div class="layui-public-input">'+
                                    '<input type="text" id="cooperativeName" name="cooperativeName" required lay-verify="required" placeholder="请输入合作伙伴名称" autocomplete="off" class="layui-input">'+
                                '</div>'+
                            '</div>'+
                            '<div class="layui-form-item layui-input-container taxIdentificationNumber-container">'+
                                '<div class="layui-public-input">'+
                                    '<input type="text" id="cooperativeUrl" name="cooperativeUrl" lay-verify="" placeholder="请输入链接地址" autocomplete="off" class="layui-input">'+
                                '</div>'+
                            '</div>'+
                            '<div class="layui-form-item layui-input-container taxIdentificationNumber-container">'+
                                '<div class="layui-public-input">'+
                                    '<input type="number" id="sort" name="sort" required lay-verify="sortNum" placeholder="请输入排序编号" autocomplete="off" class="layui-input">'+
                                '</div>'+
                            '</div>'+
                            '<div class="layui-form-item layui-input-container taxIdentificationNumber-container">'+
                                '<div class="layui-public-input">'+
                                    	'<img class="layui-img-show" src="images/u11930.png" id="picUrl">'+
								    	'<a class="layui-img-submit" id="imgSubmitBtn">上传LOGO</a>'+
								    	'<input type="file" class="layui-img-file" id="file">'+
								    	'<input type="text" name="logoUrl" id="logoUrl" lay-verify="logoUrl" style="display:none">'+
                                '</div>'+
                            '</div>'+
                            '<div class="layui-form-item layui-input-container layui-btn-container">'+
                                '<div class="layui-public-input layui-public-btn">'+
                                    '<button type="button" class="layui-btn layui-submit-btn" lay-submit lay-filter="bizNewsSubmitBtn" id="bizNewsSubmitBtn" >提交</button>'+
                                '</div>'+
                            '</div>'+
                        '</form>';

	var popupTitle ='<span class="layui-breadcrumb " lay-separator=">" style="visibility: visible;">'+
						'<a><cite>合作伙伴管理</cite>'+
						'</a><span lay-separator="">&gt;</span>'+
						'<a><cite>'+headTitle+'</cite></a>'+
			        '</span>';
    var open = layer.open({
        type: 1,
        resize: false,
        area: ['480px','450px'],
        title: popupTitle,
        content : popupContent,
        cancel: function(index, layero){ 
        }    
    });

    // 上传图片按钮
    $("#imgSubmitBtn").click(function(){
		$("#file").click()
	}) 

	// 显示上传的图片
	$("#file").change(function(){
		// 判断文件上传类型是否为图片类型
		var fileTypes = [".jpg", ".png", ".jpeg", ".gif", ".bmp"];  
		var filePath  = $(this).val();
		var isNext = false;  
		if (filePath) {
			var fileEnd = filePath.substring(filePath.indexOf(".")); 
			for (var i = 0; i < fileTypes.length; i++) {
				if(fileEnd.toLowerCase() == fileTypes[i]){
					isNext = true;
				}
			}
		}
		if (isNext) {
			var imgFile = this.files[0];
		    var fr = new FileReader();
		    fr.onload = function() {
		        $("#picUrl").attr("src", fr.result);
		    };
		    fr.readAsDataURL(imgFile);
		    var loading = layer.load(2, {time: 0}); 
			uploadPublicFile(loading);
		} else {
			layer.msg('图片格式不正确！', { time: 1000 });
		}
	})	

    // 渲染
    layui.use('form', function(){
        var form = layui.form; 
        form.render();   
        // 校验
		form.verify({
			sortNum: function(value, item){ //value：表单的值、item：表单的DOM对象
				if (value=="") {
 					return "请输入资讯排序编号！";
				}
				if (checkNumber(value) == false) {
 					return "请输入正确的数字格式！";
				}
			},
			logoUrl: function(value, item){
				if(value == ""){
					return "请上传LOGO！";
				}
			}
		}); 
    	// 新增/修改数据提交 
		form.on('submit(bizNewsSubmitBtn)', function(thisData){
			var data = convertUrlParamStrToJSON($("#cooperativeForm").serialize());
			if ($("#bizNewsSubmitBtn").is("button[operateState]") && $("#bizNewsSubmitBtn").attr("operateState") == "edit"){
				data.id = $("#bizNewsSubmitBtn").attr("editid");
			}
			data.releaseTime =  new Date().getTime();
			operateCooperativeData(data, open);
		}); 
    });


    // 判断网址输入值是否存在http
	$("#cooperativeUrl").change(function(){
		if($(this).val()!="" && $(this).val().indexOf("http") == -1){
			$(this).val("http://"+$(this).val()); 
		}
	})
}

// 查询数据
$("#searchDataBtn").click(function(){
	var data = convertUrlParamStrToJSON($("#searchForm").serialize());
	createCooperative(data,1);
})

// 新增、修改数据
function operateCooperativeData(data, open){
	postJsonWithConsoleHeaderToken(api_config.save_Portal_Cooperative, data, function(jsonData){ 
	    if(jsonData.resultCode==200){
	        createCooperative();
	        layer.close(open);
	    }else{
	        // alert("您已经久未操作,请重新登录!",gotoLogin());
	    }
	});
}

//上传图片
function uploadPublicFile(loading){
	var formData = new FormData();
	formData.append('limitSize','3000'); // 设置文件大小
	formData.append('savePath','image/news'); // 存放地址
	formData.append('file', $('#file')[0].files[0]); // $('#?') 上传按钮
	postFileWithConsoleHeaderToken(api_config.upload_public_file, formData, function(jsonResult){
		// console.log(JSON.stringify(jsonResult));
		if(jsonResult.resultCode=="200"){
			console.log(jsonResult.url);
			$('#logoUrl').val(jsonResult.url);
			layer.close(loading)
			// system_config.public_file_host_url 地址前缀, jsonResult.url 传入后台的值
		}
	});
}
